import { reqWeatherApi } from '@/api/common'
import useWeatherStore from '@/store/hooks/useWeatherStore'
import { OK_CODE } from '@/app/keys'

export const useWeatherData = () => {
  const weatherStore = useWeatherStore()
  const loading = ref(true)
  const weather_data = ref('')

  watch(() => weatherStore.city, async (city) => {
    if (!city) return
    try {
      const { code, data } = await reqWeatherApi(city)
      if (code === OK_CODE) {
        const wea = JSON.parse(data)
        weather_data.value = wea?.data?.weather?.content
        weatherStore.load(weather_data.value)
      }
      loading.value = false
    } catch (error) {
      loading.value = false
      console.log(error)
    }
  }, {
    immediate: true
  })

  return {
    loading,
    weather_data,
  }
}
